import {createSlice} from '@reduxjs/toolkit'
import { removeToken, request } from '@/utils'
import { setToken as _setToken ,getToken} from '@/utils'
import { loginAPI, userInfoAPI } from '@/apis/user'


const userStore = createSlice({
  name:'user',
  initialState:{
    token:getToken() ? getToken() :'',
    userInfo:{}
  },
  reducers:{
    setToken(state,action){
    state.token = action.payload
    console.log(state.token)
      _setToken(action.payload)
    },
    setUserInfo(state,action){
    state.userInfo = action.payload
    console.log(state.userInfo)
    },
    clearUserInfo(state){
    state.userInfo = {}
    state.token = ''
    removeToken()
    }
  }
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions

//异步请求，return一个回调，形参是dispatch
const FetchToken = (data)=>{
  return async (dispatch)=>{
    const res = await loginAPI(data)
    dispatch(setToken(res.data.data.token))
  }
}

//异步请求，return一个回调，形参是dispatch,获取用户信息
const FetchUserInfo = () => {
  return async (dispatch) => {
    const res = await userInfoAPI()
    dispatch(setUserInfo(res.data.data))
  }
}

const userReducer = userStore.reducer
export{
  setToken,
  FetchToken,
  FetchUserInfo,
  clearUserInfo
}

export default userReducer